import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/set-token'

const service = axios.create({
  baseURL: 'http://manager.webapi.rsm.alick.wang/api/', // 基本地址
  timeout: 1000000 // 超时
})

service.interceptors.request.use(
  config => {
    if (store.getters.token) { // 在头部添加token
      // config.headers.Authorization = getToken()
      config.headers.Authorization = getToken()
    }
    return config
  },
  error => { // 打印错误信息
    console.log(error)
    return Promise.reject(error)
  }
)

service.interceptors.response.use(
  response => {
    const res = response.data
    if (response.status !== 200) { // 收到200表示正确，这里是不正确的情况
      Message({
        message: res.message || 'Error',
        type: 'error',
        duration: 5 * 1000
      })

      // 50008: 非法请求; 50012: 其他客户端登陆; 50014: Token过期;
      if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
        // 重新登陆
        MessageBox.confirm('You have been logged out, you can cancel to stay on this page, or log in again', 'Confirm logout', {
          confirmButtonText: 'Re-Login',
          cancelButtonText: 'Cancel',
          type: 'warning'
        }).then(() => {
          store.dispatch('user/resetToken').then(() => {
            location.reload()
          })
        })
      }
      return Promise.reject(new Error(res.message || 'Error'))// 错误信息
    } else { // 这里表示正确的情况
      if (res.code < 0) {
        Message({
          message: res.message || 'Error',
          type: 'error',
          duration: 5 * 1000
        })
        return Promise.reject(new Error(res.message || 'Error'))
      }
      return res// 到这里才返回信息
    }
  },
  error => {
    console.log('err' + error) // 输出错误信息
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
